import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';

class NavTool {
  static FluroRouter router;

  /// 设置路由对象
  static void setRouter(FluroRouter router) {
    router = router;
  }

  /// 跳转到首页
  static void goRoot(BuildContext context) {
    router.navigateTo(context, "/", replace: true, clearStack: true);
  }

  /// 跳转到指定地址
  static void push(BuildContext context, String path,
      {bool replace = false, bool clearStack = false}) {
    FocusScope.of(context).unfocus();
    router.navigateTo(context, path,
        replace: replace,
        clearStack: clearStack,
        transition: TransitionType.native);
  }

  /// 跳转到指定地址，有回调
  static void pushResult(
      BuildContext context, String path, Function(Object) function,
      {bool replace = false, bool clearStack = false}) {
    FocusScope.of(context).unfocus();
    router
        .navigateTo(context, path,
            replace: replace,
            clearStack: clearStack,
            transition: TransitionType.native)
        .then((value) {
      if (value == null) {
        return;
      }
      function(value);
    }).catchError((onError) {
      print("$onError");
    });
  }

  /// 跳转到指定地址-传参
  static void pushArgumentResult(BuildContext context, String path,
      Object argument, Function(Object) function,
      {bool replace = false, bool clearStack = false}) {
    router
        .navigateTo(context, path,
            routeSettings: RouteSettings(arguments: argument),
            replace: replace,
            clearStack: clearStack)
        .then((value) {
      if (value == null) {
        return;
      }
      function(value);
    }).catchError((onError) {
      print("$onError");
    });
  }

  /// 跳转到指定地址-传参
  static void pushArgument(BuildContext context, String path, Object argument,
      {bool replace = false, bool clearStack = false}) {
    router.navigateTo(context, path,
        routeSettings: RouteSettings(arguments: argument),
        replace: replace,
        clearStack: clearStack);
  }

  /// 回退
  static void goBack(BuildContext context) {
    FocusScope.of(context).unfocus();
    Navigator.pop(context);
  }

  static void goBackWithParams(BuildContext context, result) {
    FocusScope.of(context).unfocus();
    Navigator.pop(context, result);
  }

  /// 替换当前地址
  static String changeToNavigatorPath(String registerPath,
      {Map<String, Object> params}) {
    if (params == null || params.isEmpty) {
      return registerPath;
    }
    StringBuffer bufferStr = StringBuffer();
    params.forEach((key, value) {
      bufferStr
        ..write(key)
        ..write("=")
        ..write(Uri.encodeComponent(value))
        ..write("&");
    });
    String paramStr = bufferStr.toString();
    paramStr = paramStr.substring(0, paramStr.length - 1);
    print("传递的参数  $paramStr");
    return "$registerPath?$paramStr";
  }
}
